﻿using CommunityToolkit.Mvvm.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Vision.Abstractions;
using Vision.Abstractions.Events;
using Vision.Devices;

namespace Vision.UI.ViewModels
{
	/// <summary>
	/// 消费图像总线并在 UI 上展示源图像的 ViewModel。
	/// </summary>
	public partial class ProcessingViewModel : ObservableObject
	{
        private readonly IEventAggregator _eventAggregator;

        [ObservableProperty]
		private ImageSource? _sourceImage;

        [ObservableProperty]
        private ImageSource? _processedImage;


        /// <summary>
        /// 构造函数，注入图像总线与相机。
        /// </summary>
        public ProcessingViewModel(IEventAggregator eventAggregator)
		{
            _eventAggregator = eventAggregator;

            // 订阅原图像事件
            _eventAggregator.GetEvent<SourceImageEvent>().Subscribe(OnSourceImageReceived);

            // 订阅处理后图像事件
            _eventAggregator.GetEvent<ProcessedImageEvent>().Subscribe(OnProcessedImageReceived);
		}

		private async void OnSourceImageReceived(CameraFrameMessage frame)
		{
			var bitmap = CreateBitmapSource(frame.ImageData, frame.Width, frame.Height);
			bitmap.Freeze();
			await App.Current.Dispatcher.InvokeAsync(() => { SourceImage = bitmap; });
		}
        private async void OnProcessedImageReceived(CameraFrameMessage frame)
        {
            var bitmap = CreateBitmapSource(frame.ImageData, frame.Width, frame.Height);
            bitmap.Freeze();
            await App.Current.Dispatcher.InvokeAsync(() => { ProcessedImage = bitmap; });
        }
        private static BitmapSource CreateBitmapSource(byte[] imageData, int width, int height)
		{
			return BitmapSource.Create(width, height, 96, 96, PixelFormats.Gray8, null, imageData, width);
		}
	}
}